import { BaseContext } from "koa";
export const router = require("koa-router")();
export enum Methods {
  get = "get",
  post = "post",
}
const authMiddleware = (controller: any) => {
  return (ctx: BaseContext, next: any) => {
    const authorize = controller.authorize;
    if (authorize && typeof authorize === "function") {
      return authorize.call(null, ctx, next);
    }
    return next();
  };
};

const getRequestDecorator = (type: Methods) => {
  return (path: string) => {
    return (target: any, key: string) => {
      const controller = target[key];
      Reflect.defineMetadata('path', path, target, key);
      Reflect.defineMetadata('method', type, target, key);
      Reflect.defineMetadata('middlewares', authMiddleware(controller), target, key);
    };
  };
}

export const Get = getRequestDecorator(Methods.get);
export const Post = getRequestDecorator(Methods.post);


// 类路由装饰器
export const Controller = (root: string) => {
  return (target:any) => {
    for (let key in target.prototype) {
      const path: string = Reflect.getMetadata('path', target.prototype, key);
      const method: Methods = Reflect.getMetadata('method', target.prototype, key);
      const middlewares:any = Reflect.getMetadata('middlewares', target.prototype, key);
      const handler = target.prototype[key];
      if (path && method) {
        const fullPath = root === '/' ? path : `${root}${path}`;
        if (middlewares) {
          router[method](fullPath, middlewares, handler);
        } else {
          router[method](fullPath, handler);
        }
      }
    }
  };
}
